package com.alogic.pipeline.impl;

import com.alogic.pipeline.PipelineListener;
import com.alogic.pipeline.PipelineStage;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.Script;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.util.*;
import org.w3c.dom.Element;
import java.util.HashMap;

/**
 * 基于脚本执行的Stage
 *
 * @since 1.6.13.35 [20210218 duanyy] <br>
 */
public class ScriptStage extends PipelineStage.Base {
    protected Logiclet script = null;

    @Override
    public void run(String jobId, Properties ctx, PipelineListener listener) {
        if (script != null){
            LogicletContext logicletContext = new LogicletContext(ctx);
            try {
                XsObject doc = new JsonObject("root",new HashMap<String,Object>());
                script.execute(doc,doc, logicletContext, null);
                ctx.SetValue("$state",
                        PropertiesConstants.getString(
                                logicletContext,"$state","ok",true));
                ctx.SetValue("$stateMessage",
                        PropertiesConstants.getString(
                                logicletContext,"$stateMessage","ok",true));
            }catch (Exception ex){
                ctx.SetValue("$state","failed");
                ctx.SetValue("$stateMessage",ex.getMessage());
            }
        }
    }

    @Override
    public void configure(Element e, Properties p) {
        XmlElementProperties props = new XmlElementProperties(e,p);
        configure(props);
        loadPairs(e,p);

        Element elem = XmlTools.getFirstElementByPath(e, "script");
        if (elem != null){
            script = Script.create(elem, props);
        }
    }
}
